package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// PaymentTransactionController 处理支付交易记录相关请求
type PaymentTransactionController struct {
	web.Controller
}

// List 获取交易记录列表
func (c *PaymentTransactionController) List() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 交易流水号
	if transactionNo := c.GetString("transactionNo"); transactionNo != "" {
		filters["transaction_no"] = transactionNo
	}

	// 订单号
	if orderNo := c.GetString("orderNo"); orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 用户名
	if username := c.GetString("username"); username != "" {
		// 根据用户名查找会员ID
		member, err := models.GetMemberByName(username, user.FranchiseId)
		if err == nil && member != nil {
			filters["member_id"] = member.Id
		}
	}

	// 交易类型
	if transactionType := c.GetString("type"); transactionType != "" {
		// 将前端的字符串类型转换为后端的数字类型
		var typeValue int8
		switch transactionType {
		case "payment":
			typeValue = 1 // 支付
		case "refund":
			typeValue = 2 // 退款
		case "recharge":
			typeValue = 3 // 充值
		case "withdraw":
			typeValue = 4 // 提现
		}
		filters["type"] = typeValue
	}

	// 支付渠道
	if channelId := c.GetString("channelId"); channelId != "" {
		// 获取支付渠道信息
		filters["payment_channel"] = channelId
	}

	// 交易状态
	if status := c.GetString("status"); status != "" {
		// 将前端的字符串状态转换为后端的数字状态
		var statusValue int8
		switch status {
		case "pending":
			statusValue = 0 // 处理中
		case "success":
			statusValue = 1 // 成功
		case "failed":
			statusValue = 2 // 失败
		}
		filters["status"] = statusValue
	}

	// 时间范围
	if startTime := c.GetString("startTime"); startTime != "" {
		// 将前端的时间字符串转换为时间戳
		start, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
		if err == nil {
			filters["start_time"] = start.Unix()
		}
	}

	if endTime := c.GetString("endTime"); endTime != "" {
		// 将前端的时间字符串转换为时间戳
		end, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
		if err == nil {
			filters["end_time"] = end.Unix()
		}
	}

	// 获取交易记录列表
	transactions, total, err := models.GetTransactionList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取交易记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 构建响应数据
	list := make([]map[string]interface{}, 0)
	for _, transaction := range transactions {
		// 获取会员信息
		member, _ := models.GetMemberById(transaction.MemberId, user.FranchiseId)
		username := ""
		if member != nil {
			username = member.Name
		}

		// 获取支付渠道名称
		channelName := transaction.PaymentChannel

		// 转换交易类型为前端格式
		transactionType := ""
		switch transaction.Type {
		case 1:
			transactionType = "payment" // 支付
		case 2:
			transactionType = "refund" // 退款
		case 3:
			transactionType = "recharge" // 充值
		case 4:
			transactionType = "withdraw" // 提现
		}

		// 转换交易状态为前端格式
		transactionStatus := ""
		switch transaction.Status {
		case 0:
			transactionStatus = "pending" // 处理中
		case 1:
			transactionStatus = "success" // 成功
		case 2:
			transactionStatus = "failed" // 失败
		}

		// 格式化时间
		createdAt := time.Unix(transaction.CreatedAt, 0).Format("2006-01-02 15:04:05")
		finishedAt := ""
		if transaction.CompletionTime > 0 {
			finishedAt = time.Unix(transaction.CompletionTime, 0).Format("2006-01-02 15:04:05")
		}

		item := map[string]interface{}{
			"id":            transaction.Id,
			"transactionNo": transaction.TransactionNo,
			"orderNo":       transaction.OrderNo,
			"username":      username,
			"amount":        transaction.Amount,
			"channelName":   channelName,
			"type":          transactionType,
			"status":        transactionStatus,
			"createdAt":     createdAt,
			"finishedAt":    finishedAt,
			"thirdPartyNo":  transaction.ChannelTradeNo,
			"remark":        transaction.Remark,
		}

		list = append(list, item)
	}

	// 返回交易记录列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易记录列表成功",
		"data":    list,
		"total":   total,
		"page":    page,
		"size":    pageSize,
	}
	c.ServeJSON()
}

// GetOne 获取交易记录详情
func (c *PaymentTransactionController) GetOne() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取交易记录ID
	id, err := c.GetInt64(":id")
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的交易记录ID",
		}
		c.ServeJSON()
		return
	}

	// 获取交易记录详情
	transaction, err := models.GetTransactionById(id, user.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取交易记录详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, _ := models.GetMemberById(transaction.MemberId, user.FranchiseId)
	username := ""
	if member != nil {
		username = member.Name
	}

	// 获取支付渠道名称
	channelName := transaction.PaymentChannel

	// 转换交易类型为前端格式
	transactionType := ""
	switch transaction.Type {
	case 1:
		transactionType = "payment" // 支付
	case 2:
		transactionType = "refund" // 退款
	case 3:
		transactionType = "recharge" // 充值
	case 4:
		transactionType = "withdraw" // 提现
	}

	// 转换交易状态为前端格式
	transactionStatus := ""
	switch transaction.Status {
	case 0:
		transactionStatus = "pending" // 处理中
	case 1:
		transactionStatus = "success" // 成功
	case 2:
		transactionStatus = "failed" // 失败
	}

	// 格式化时间
	createdAt := time.Unix(transaction.CreatedAt, 0).Format("2006-01-02 15:04:05")
	finishedAt := ""
	if transaction.CompletionTime > 0 {
		finishedAt = time.Unix(transaction.CompletionTime, 0).Format("2006-01-02 15:04:05")
	}

	// 构建响应数据
	data := map[string]interface{}{
		"id":            transaction.Id,
		"transactionNo": transaction.TransactionNo,
		"orderNo":       transaction.OrderNo,
		"username":      username,
		"amount":        transaction.Amount,
		"channelName":   channelName,
		"type":          transactionType,
		"status":        transactionStatus,
		"createdAt":     createdAt,
		"finishedAt":    finishedAt,
		"thirdPartyNo":  transaction.ChannelTradeNo,
		"description":   "", // 交易描述，可以根据需要添加
		"remark":        transaction.Remark,
		"rawData":       transaction.RawData,
	}

	// 返回交易记录详情
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易记录详情成功",
		"data":    data,
	}
	c.ServeJSON()
}
